/* eslint-disable */
/*
 * @Description: 其他工具函数
 * @Author:
 * @Date:
 * @LastEditors: dh
 */

// 证件号码脱敏显示
export const cardNumberShow = number => {
	if (!number) {
		return;
	}
	let pat = /(\w{3})\w*(\w{4})/;
	if (number.length < 10) {
		pat = /(\w{2})\w*(\w{3})/;
	}
	const str = number.replace(pat, "$1****$2");
	return str;
};

// 获取一个url参数
export const getOneUrlParams = name => {
	const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	const search = window.location.search.split("?")[1] || "";
	const r = search.match(reg) || [];
	return r[2];
};

// 获取全部的url参数
export function getAllUrlParams(url) {
	const paramsStr = /.+\?(.+)$/.exec(url)[1]; // 将 ? 后面的字符串取出来
	const paramsArr = paramsStr.split("&"); // 将字符串以 & 分割后存到数组中
	let paramsObj = {};
	// 将 params 存到对象中
	paramsArr.forEach(param => {
		if (/=/.test(param)) {
			// 处理有 value 的参数
			let [key, val] = param.split("="); // 分割 key 和 value
			val = decodeURIComponent(val); // 解码
			val = /^\d+$/.test(val) ? parseFloat(val) : val; // 判断是否转为数字

			if (paramsObj.hasOwnProperty(key)) {
				// 如果对象有 key，则添加一个值
				paramsObj[key] = [].concat(paramsObj[key], val);
			} else {
				// 如果对象没有这个 key，创建 key 并设置值
				paramsObj[key] = val;
			}
		} else {
			// 处理没有 value 的参数
			paramsObj[param] = "";
		}
	});

	return paramsObj;
}

// 追加url参数
export const addUrlParams = (url, key, value) => {
	let options = key;
	if (typeof options == "string") {
		options = {};
		options[key] = value;
	}
	options = $.param(options);
	if (url.includes("?")) {
		url += "&" + options;
	} else {
		url += "?" + options;
	}
	return url;
};

// 动态引入js
export const injectScript = src => {
	const s = document.createElement("script");
	s.type = "text/javascript";
	s.async = true;
	s.src = src;
	const t = document.getElementsByTagName("script")[0];
	t.parentNode.insertBefore(s, t);
};

// 复制粘贴
export const copyTextToClipboard = value => {
	let textArea = document.createElement("textarea");
	textArea.style.background = "transparent";
	textArea.value = value;
	document.body.appendChild(textArea);
	textArea.select();
	try {
		let successful = document.execCommand("copy");
	} catch (err) {
		console.log("Oops, unable to copy");
	}
	document.body.removeChild(textArea);
};

/* 数组去重 */
export const unique = arr => {
	if (Array.hasOwnProperty("from")) {
		return Array.from(new Set(arr));
	} else {
		let n = {},
			r = [];
		for (let i = 0; i < arr.length; i++) {
			if (!n[arr[i]]) {
				n[arr[i]] = true;
				r.push(arr[i]);
			}
		}
		return r;
	}
};
// 洗牌算法随机
export const shuffle = arr => {
	let result = [],
		random;
	while (arr.length > 0) {
		random = Math.floor(Math.random() * arr.length);
		result.push(arr[random]);
		arr.splice(random, 1);
	}
	return result;
};

// 将阿拉伯数字翻译成中文的大写数字
export const numberToChinese = num => {
	let AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
	let BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");
	let a = ("" + num).replace(/(^0*)/g, "").split("."),
		k = 0,
		re = "";
	for (var i = a[0].length - 1; i >= 0; i--) {
		switch (k) {
			case 0:
				re = BB[7] + re;
				break;
			case 4:
				if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$").test(a[0])) re = BB[4] + re;
				break;
			case 8:
				re = BB[5] + re;
				BB[7] = BB[5];
				k = 0;
				break;
		}
		if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re;
		if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
		k++;
	}

	if (a.length > 1) {
		// 加上小数部分(如果有小数部分)
		re += BB[6];
		for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
	}
	if (re == "一十") re = "十";
	if (re.match(/^一/) && re.length == 3) re = re.replace("一", "");
	return re;
};

/* 判断元素是否有指定类名 */
export function hasClass(ele, cls) {
	return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/* 向元素添加类名 */
export function addClass(ele, cls) {
	if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/* 移除元素指定类名 */
export function removeClass(ele, cls) {
	if (hasClass(ele, cls)) {
		const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
		ele.className = ele.className.replace(reg, " ");
	}
}

/*有类名就删除，否则添加  */
export function toggleClass(element, className) {
	if (!element || !className) {
		return;
	}
	let classString = element.className;
	const nameIndex = classString.indexOf(className);
	if (nameIndex === -1) {
		classString += "" + className;
	} else {
		classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length);
	}
	element.className = classString;
}

/* 创建独一无二的string、随机id */
export function createUniqueString() {
	const timestamp = +new Date() + "";
	const randomNum = parseInt((1 + Math.random()) * 65536) + "";
	return (+(randomNum + timestamp)).toString(32);

	// or
	// return Math.random().toString(36).substr(2);
}

// 去除 html 标签
export const removeHtmltag = str => {
	// const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
	return str.replace(/<[^>]+>/g, "");
};

// 标签过滤替换
export function filterTag(str) {
	str = str.replace(/&/gi, "&");
	str = str.replace(/</gi, "<");
	str = str.replace(/>/gi, ">");
	str = str.replace(" ", " ");
	return str;
}
// 百度坐标转高德（传入经度、纬度）
export const BMapTransformAMap = function (bdlng, bdlat) {
	const X_PI = (Math.PI * 3000.0) / 180.0;
	const x = bdlng - 0.0065;
	const y = bdlat - 0.006;
	const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
	const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
	const gglng = z * Math.cos(theta);
	const gglat = z * Math.sin(theta);
	return {
		lng: gglng,
		lat: gglat,
	};
};

// 高德坐标转百度（传入经度、纬度）
export const AMapTransformBMap = function (gglng, gglat) {
	const X_PI = (Math.PI * 3000.0) / 180.0;
	const x = gglng;
	const y = gglat;
	const z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI);
	const theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI);
	const bdlng = z * Math.cos(theta) + 0.0065;
	const bdlat = z * Math.sin(theta) + 0.006;
	return {
		lat: bdlat,
		lng: bdlng,
	};
};

// 加法函数（精度丢失问题） 第三方Math.js、big.js
export function add(arg1, arg2) {
	let r1, r2, m;
	try {
		r1 = arg1.toString().split(".")[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = arg2.toString().split(".")[1].length;
	} catch (e) {
		r2 = 0;
	}
	m = Math.pow(10, Math.max(r1, r2));
	return (arg1 * m + arg2 * m) / m;
}

// 减法函数（精度丢失问题）
export function sub(arg1, arg2) {
	let r1, r2, m, n;
	try {
		r1 = arg1.toString().split(".")[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = arg2.toString().split(".")[1].length;
	} catch (e) {
		r2 = 0;
	}
	m = Math.pow(10, Math.max(r1, r2));
	n = r1 >= r2 ? r1 : r2;
	return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
}

/**
 * 彩色打印
 * @param {string} log 打印信息
 * @param {string} color 颜色
 */
export const colorfulConsole = function () {
	let logInfo;
	let color;
	let args = arguments;
	logInfo = "%c" + (args[0] || "");
	color = "color:" + (args[1] || "red");
	console.log(logInfo, color);
	return null;
};

/**
 * 获取样式
 * @param {bode} el 元素
 * @param {string} attr 样式
 */
export function getStyle(el, attr) {
	if (el.currentStyle) {
		return el.currentStyle[attr];
	} else {
		return getComputedStyle(el, false)[attr];
	}
}

/**
 * 判断是不是JSON
 * @param  str 字符串
 */
export function isJSON(str) {
	if (typeof str == "string") {
		try {
			let obj = JSON.parse(str);
			if (typeof obj == "object" && obj) {
				return true;
			} else {
				return false;
			}
		} catch (e) {
			return false;
		}
	}
}

/**
 * @description: 对象转化为formData
 * @param {Object} object
 * @return {formData}
 */
export function getFormData(object) {
	const formData = new FormData();
	Object.keys(object).forEach(key => {
		const value = object[key];
		if (Array.isArray(value)) {
			value.forEach((subValue, i) => formData.append(key + `[${i}]`, subValue));
		} else {
			formData.append(key, object[key]);
		}
	});
	return formData;
}

// 加密为base64
function utf8_to_b64(str) {
	return window.btoa(unescape(encodeURIComponent(str)));
}
// 解密
function b64_to_utf8(str) {
	return decodeURIComponent(escape(window.atob(str)));
}

// 获取元素坐在页面位置
export function getRect(el) {
	if (el instanceof window.SVGElement) {
		let rect = el.getBoundingClientRect();
		return {
			top: rect.top,
			left: rect.left,
			width: rect.width,
			height: rect.height,
		};
	} else {
		return {
			top: el.offsetTop,
			left: el.offsetLeft,
			width: el.offsetWidth,
			height: el.offsetHeight,
		};
	}
}

// 转移特殊字符，防止xss
export const escapeHTML = str => {
	str.replace(
		/[&<>'"]/g,
		tag =>
			({
				"&": "&amp;",
				"<": "&lt;",
				">": "&gt;",
				"'": "&#39;",
				'"': "&quot;",
			}[tag] || tag)
	);
};

// H5软键盘缩回、弹起回调
//当软件键盘弹起会改变当前 window.innerHeight，监听这个值变化 [downCb 当软键盘弹起后，缩回的回调,upCb 当软键盘弹起的回调]
function h5Resize(downCb, upCb) {
	let clientHeight = window.innerHeight;
	downCb = typeof downCb === "function" ? downCb : function () {};
	upCb = typeof upCb === "function" ? upCb : function () {};
	window.addEventListener("resize", () => {
		let height = window.innerHeight;
		if (height === clientHeight) {
			downCb();
		}
		if (height < clientHeight) {
			upCb();
		}
	});
}

// 去除字符串空格
export function trim(str, type = 1) {
	// 去除空格， type:  1-所有空格  2-前后空格  3-前空格 4-后空格
	switch (type) {
		case 1:
			return str.replace(/\s+/g, "");
		case 2:
			return str.replace(/(^\s*)|(\s*$)/g, "");
		case 3:
			return str.replace(/(^\s*)/g, "");
		case 4:
			return str.replace(/(\s*$)/g, "");
		default:
			return str;
	}
}

// 本地存储
const store = {
	set: function (name, value, day) {
		// 设置
		let d = new Date();
		let time = 0;
		day = typeof day === "undefined" || !day ? 1 : day; // 时间,默认存储1天
		time = d.setHours(d.getHours() + 24 * day); // 毫秒
		localStorage.setItem(
			name,
			JSON.stringify({
				data: value,
				time: time,
			})
		);
	},
	get: function (name) {
		// 获取
		let data = localStorage.getItem(name);
		if (!data) {
			return null;
		}
		let obj = JSON.parse(data);
		if (new Date().getTime() > obj.time) {
			// 过期
			localStorage.removeItem(name);
			return null;
		} else {
			return obj.data;
		}
	},
	clear: function (name) {
		// 清空
		if (name) {
			// 删除键为name的缓存
			localStorage.removeItem(name);
		} else {
			// 清空全部
			localStorage.clear();
		}
	},
};

/**
 *Created by PanJiaChen on 16/11/29.
 * @param {Sting} url
 * @param {Sting} title
 * @param {Number} w
 * @param {Number} h
 */
export function openWindow(url, title, w, h) {
	// Fixes dual-screen position                            Most browsers       Firefox
	const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
	const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

	const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
	const height = window.innerHeight
		? window.innerHeight
		: document.documentElement.clientHeight
		? document.documentElement.clientHeight
		: screen.height;

	const left = width / 2 - w / 2 + dualScreenLeft;
	const top = height / 2 - h / 2 + dualScreenTop;
	const newWindow = window.open(
		url,
		title,
		"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=" +
			w +
			", height=" +
			h +
			", top=" +
			top +
			", left=" +
			left
	);

	// Puts focus on the newWindow
	if (window.focus) {
		newWindow.focus();
	}
}
